package br.com.rafsoft.mapaentrega.activity.async;

import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import br.com.rafsoft.mapaentrega.MapaEntregaApplication;
import br.com.rafsoft.mapaentrega.Util;
import br.com.rafsoft.mapaentrega.activity.TaskListActivity;
import br.com.rafsoft.mapaentrega.shared.MapaEntregaRequestFactory;
import br.com.rafsoft.mapaentrega.shared.TaskProxy;

import com.google.web.bindery.requestfactory.shared.Receiver;

public class AsyncFetchTask extends AsyncTask<Long, Void, List<TaskProxy>> {

	private final TaskListActivity activity;
	private boolean newTask = false;

	public AsyncFetchTask(TaskListActivity activity) {
		super();
		this.activity = activity;
	}

	@Override
	protected List<TaskProxy> doInBackground(Long... arguments) {
		final List<TaskProxy> list = new ArrayList<TaskProxy>();

		// INSERT RPC HERE!
		MapaEntregaRequestFactory factory = Util.getRequestFactory(activity,
				MapaEntregaRequestFactory.class);

		if (arguments.length == 0 || arguments[0] == -1) {
			MapaEntregaApplication application = (MapaEntregaApplication) activity.getApplication();
			factory.taskRequest().queryTasksUser(application.getUser())
					.fire(new Receiver<List<TaskProxy>>() {
						@Override
						public void onSuccess(List<TaskProxy> arg0) {
							list.addAll(arg0);
							//activity.setTasks(arg0);
						}
					});
		} else {
			newTask = true;
			factory.taskRequest().readTask(arguments[0])
					.fire(new Receiver<TaskProxy>() {

						@Override
						public void onSuccess(TaskProxy arg0) {
							list.add(arg0);
						}
					});
		}

		return list;
	}

	@Override
	protected void onPostExecute(List<TaskProxy> result) {
		if (newTask) {
			activity.addTasks(result);
		} else {
			activity.setTasks(result);
		}
	}
}
